<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
<!--      <el-form-item label="菜单id" prop="menuId">
        <el-input
          v-model="queryParams.menuId"
          placeholder="请输入菜单id"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>-->
      <el-form-item label="菜单名称" prop="menuName">
        <el-input
          v-model="queryParams.menuName"
          placeholder="请输入菜单名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="父级菜单id" prop="parentId">
        <el-input
          v-model="queryParams.parentId"
          placeholder="请输入父级菜单id"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>-->
      <el-form-item label="点击量" prop="clickCount">
        <el-input
          v-model="queryParams.clickCount"
          placeholder="请输入点击量"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="显示顺序" prop="orderNum">
        <el-input
          v-model="queryParams.orderNum"
          placeholder="请输入显示顺序"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="渲染状态" prop="status" style="width: 250px;">
        <el-select v-model="queryParams.status" placeholder="请选择渲染状态" clearable @change="handleQuery">
          <el-option
            v-for="dict in sys_menuorclass_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
<!--      <el-form-item label="管理员id" prop="adminId">
        <el-input
          v-model="queryParams.adminId"
          placeholder="请输入管理员id"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>-->
      <el-form-item label="时间范围" style="width: 308px">
        <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['tmenu:tmenu:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Sort"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="tmenuList"
      row-key="menuId"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      stripe
    >
      <el-table-column label="菜单名称" prop="menuName" />
      <el-table-column label="id" prop="menuId" width="100" />
      <el-table-column label="父级菜单" align="center" prop="parentId" width="100" />
      <el-table-column label="点击量" align="center" prop="clickCount" width="100" />
      <el-table-column label="显示顺序" align="center" prop="orderNum" width="100" />
      <el-table-column label="渲染状态" align="center" prop="status" width="100">
        <template #default="scope">
          <dict-tag :options="sys_menuorclass_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
<!--      <el-table-column label="管理员id" align="center" prop="adminId" />-->
      <el-table-column label="管理员" align="center" prop="adminName" width="100" show-overflow-tooltip/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="120" show-overflow-tooltip>
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}' ) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="120" show-overflow-tooltip>
        <template #default="scope">
          <span v-if="scope.row?.updateTime && scope.row.updateTime.trim() !== ''">
            {{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
          </span>
          <span v-else>
            未更新
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="300">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['tmenu:tmenu:edit']">修改</el-button>
          <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['tmenu:tmenu:add']">新增</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['tmenu:tmenu:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改菜单信息管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="tmenuRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="菜单名称" prop="menuName">
          <el-input v-model="form.menuName" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item label="父级菜单" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="tmenuOptions"
            :props="{ value: 'menuId', label: 'menuName', children: 'children' }"
            value-key="menuId"
            placeholder="请选择父级菜单id"
            check-strictly
          />
        </el-form-item>
        <el-form-item label="点击量" prop="clickCount">
          <el-input v-model="form.clickCount" placeholder="请输入点击量" />
        </el-form-item>
<!--        <el-form-item label="显示顺序" prop="orderNum">
          <el-input v-model="form.orderNum" placeholder="请输入显示顺序" />
        </el-form-item>-->
        <el-form-item label="显示顺序" prop="orderNum">
          <el-input-number
              v-model="form.orderNum"
              :min="1"
              controls-position="right"
              placeholder="请输入或选择显示顺序"
              style="width: 60%"
          />
        </el-form-item>
        <el-form-item label="渲染状态" prop="status">
<!--          <el-select v-model="form.status" placeholder="请选择渲染状态">
            <el-option
              v-for="dict in sys_menuorclass_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>-->
          <el-radio-group v-model="form.status">
            <el-radio
                v-for="dict in sys_menuorclass_status"
                :key="dict.value"
                :value="dict.value"
            >{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
<!--        <el-form-item label="管理员id" prop="adminId">
          <el-input v-model="form.adminId" placeholder="请输入管理员id" />
        </el-form-item>-->
        <el-form-item label="管理员" prop="adminId">
          <el-select
              v-model="form.adminId"
              placeholder="请选择管理员"
              clearable
              filterable
              style="width: 100%"
              :disabled="isEditMode"
          >
            <el-option
                v-for="admin in adminOptions"
                :key="admin.value"
                :label="admin.label"
                :value="admin.value"
                :disabled="admin.disabled"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Tmenu">
import { listTmenu, getTmenu, delTmenu, addTmenu, updateTmenu } from "@/api/tmenu/tmenu"
import {parseTime} from "../../../utils/ruoyi.js";
import {listAdmin} from "@/api/admin/admin.js";

const { proxy } = getCurrentInstance()
const { sys_menuorclass_status } = proxy.useDict('sys_menuorclass_status')

const tmenuList = ref([])
const tmenuOptions = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const title = ref("")
const isExpandAll = ref(true)
const refreshTable = ref(true)

//日期范围
const dateRange = ref([])
// 管理员下拉框选项
const adminOptions = ref([]);
// 添加管理员状态映射
const adminStatusMap = ref({})
const isEditMode = ref(false); //是否可编辑

const data = reactive({
  form: {},
  queryParams: {
    menuId: null,
    menuName: null,
    parentId: null,
    clickCount: null,
    orderNum: null,
    status: null,
    adminId: null,
    beginTime:null,
    endTime:null,
  },
  rules: {
    menuName: [
      { required: true, message: "菜单名称不能为空", trigger: "blur" }
    ],
    parentId: [
      { required: true, message: "父级菜单不能为空", trigger: "blur" }
    ],
    clickCount: [
      { required: true, message: "点击量不能为空", trigger: "blur" }
    ],
    orderNum: [
      {
        required: true,
        message: "显示顺序不能为空",
        trigger: "blur"
      },
      /*{
        type: 'number',
        message: "必须为数字值",
        trigger: ['blur', 'change']
      }*/
    ],
    status: [
      { required: true, message: "渲染状态不能为空", trigger: "blur" }
    ],
    adminId: [
      { required: true, message: "请选择管理员", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/*function getAdminList() {
  listAdmin().then(response => {
    adminOptions.value = response.rows.map(admin => ({
      label: admin.username,
      value: admin.adminId
    }));
    console.log(adminOptions)
  });
}*/

function getAdminList() {
  listAdmin().then(response => {
    // 构建管理员状态映射
    const statusMap = {}
    response.rows.forEach(admin => {
      statusMap[admin.adminId] = admin.status
    })
    adminStatusMap.value = statusMap

    // 构建下拉选项
    adminOptions.value = response.rows.map(admin => ({
      label: admin.status === '1' ? `${admin.username}(停用)` : admin.username,
      value: admin.adminId,
      disabled: admin.status === '1'
    }));
  });
}

/** 查询菜单信息管理列表 */
function getList() {
  loading.value = true
  listTmenu(queryParams.value).then(response => {
    tmenuList.value = proxy.handleTree(response.data, "menuId", "parentId")
    loading.value = false
  })
}

/** 查询菜单信息管理下拉树结构 */
function getTreeselect() {
  listTmenu().then(response => {
    tmenuOptions.value = []
    const data = { menuId: 0, menuName: '顶级节点', children: [] }
    data.children = proxy.handleTree(response.data, "menuId", "parentId")
    tmenuOptions.value.push(data)
  })
}
	
// 取消按钮
function cancel() {
  open.value = false
  isEditMode.value = false; // 重置编辑状态
  reset()
}

// 表单重置
function reset() {
  form.value = {
    menuId: null,
    menuName: null,
    parentId: null,
    clickCount: null,
    orderNum: null,
    status: null,
    adminId: null,
    /*createTime: null,
    updateTime: null*/
  }
  proxy.resetForm("tmenuRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  console.log(dateRange.value)
  // 设置日期范围参数
  if (dateRange.value && dateRange.value.length === 2) {
    queryParams.value.beginTime = dateRange.value[0];
    queryParams.value.endTime = `${dateRange.value[1]} 23:59:59`;
  } else {
    queryParams.value.beginTime = null;
    queryParams.value.endTime = null;
  }
  console.log(queryParams.value)
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = []
  // 重置日期参数
  queryParams.value.beginTime = null
  queryParams.value.endTime = null
  proxy.resetForm("queryRef")
  handleQuery()
}

/** 新增按钮操作 */
function handleAdd(row) {
  reset()
  form.value.status = '0' // 默认显示状态
  getTreeselect()
  if (row != null && row.menuId) {
    form.value.parentId = row.menuId
  } else {
    form.value.parentId = 0
  }
  getAdminList(); // 加载管理员列表
  isEditMode.value = false; // 新增模式不禁用
  open.value = true
  title.value = "添加菜单信息管理"
}

/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false
  isExpandAll.value = !isExpandAll.value
  nextTick(() => {
    refreshTable.value = true
  })
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset()
  await getTreeselect()
  if (row != null) {
    form.value.parentId = row.parentId
  }
  getTmenu(row.menuId).then(response => {
    form.value = response.data
    getAdminList(); // 加载管理员列表
    isEditMode.value = true; // 更新模式禁用
    open.value = true
    title.value = "修改菜单信息管理"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["tmenuRef"].validate(valid => {
    if (valid) {
      if (form.value.menuId != null) {
        updateTmenu(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addTmenu(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除菜单信息管理编号为"' + row.menuId + '"的数据项？').then(function() {
    return delTmenu(row.menuId)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

getList()
</script>
